//
//  PlistFile.m
//  YYPaas
//
//  Created by 余意 on 2018/6/26.
//  Copyright © 2018年 余意. All rights reserved.
//

#import "PlistFile.h"

@implementation PlistFile

#pragma mark - 获取Plist文件内容（字典）
+ (NSMutableDictionary *)readDictionaryPlistForKey:(NSSearchPathDirectory)searchPathDirectory WitFile:(NSString *)fileName
{
    NSArray * paths = NSSearchPathForDirectoriesInDomains(searchPathDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [NSString stringWithFormat:@"%@/",[paths firstObject]];
    
    //获取文件路径
    NSString * plistPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",fileName]];
    
    NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
    
    return dic;
}

#pragma mark - 获取Plist文件内容(数组)
+ (NSMutableArray *)readArrayPlistForKey:(NSSearchPathDirectory)searchPathDirectory WithFile:(NSString *)filename
{
    NSArray * paths = NSSearchPathForDirectoriesInDomains(searchPathDirectory, NSUserDomainMask, YES);
    NSString * documentsArray = [NSString stringWithFormat:@"%@/",[paths firstObject]];
    
    //获取文件路径
    NSString * plistPath = [documentsArray stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",filename]];
    
    NSMutableArray * array = [NSMutableArray arrayWithContentsOfFile:plistPath];
    
    return array;
}

#pragma mark - 获取document目录下文件路径
+ (NSString *)documentFilePathWithFile:(NSString *)filename
{
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * document = [paths firstObject];
    NSString * filePath = [document stringByAppendingPathComponent:filename];
    return filePath;
}

#pragma mark - 获取library目录下文件路径
+ (NSString *)libraryFilePathWithFile:(NSString *)filename
{
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString * library = [paths firstObject];
    NSString * filePath = [library stringByAppendingPathComponent:filename];
    return filePath;
}

#pragma mark - 判断文件夹是否存在
+ (BOOL)fileExistsAtPath:(NSString *)filePath
{
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        return YES;
    }
    
    return NO;
}

#pragma mark - 删除文件
- (void)deteleWithFile:(NSString *)filePath
{
    NSFileManager * defaultManager = [NSFileManager defaultManager];
    if ([defaultManager fileExistsAtPath:filePath])
    {
        [defaultManager removeItemAtPath:filePath error:nil];
    }
}

#pragma mark - 创建文件夹
+ (BOOL)creatDirectoryIfNotExistsAtPath:(NSString *)path
{
    BOOL result = NO;
    NSFileManager * fileManager = [NSFileManager defaultManager];
    BOOL exists = [fileManager fileExistsAtPath:path];
    if (!exists)
    {
        result = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    else
    {
        result = YES;
    }
    
    return result;
}

#pragma mark - 二进制数据写入文件
+ (NSString *)writeToFile:(NSData *)data WithFileName:(NSString *)filename
{
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString * documents = [paths firstObject];
    NSString * filePath = [documents stringByAppendingPathComponent:filename];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]== NO)
    {
        NSLog(@"File not exist,create it...");
        [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    }
    else
    {
        NSLog(@"File exist");
    }
    [data writeToFile:filePath atomically:YES];
    return filePath;
}

#pragma mark - 将资源文件的数据库文件写入沙盒中
+ (void)copyDatabaseIfNeededWithFile:(NSString *)fileName WithFileType:(NSString *)fileType SearchPathDirectory:(NSSearchPathDirectory)searchPathDirectory
{
    NSFileManager * fileManager = [NSFileManager defaultManager];
    NSError * error;
    
    NSArray * paths = NSSearchPathForDirectoriesInDomains(searchPathDirectory, NSUserDomainMask, YES);
    NSString * documents = [paths firstObject];
    NSString * DBPath = [documents stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",fileName,fileType]];
    BOOL isExist = [fileManager fileExistsAtPath:DBPath];
    
    if (!isExist)
    {
        //如果不存在
        NSString * defaultDBPath = [[NSBundle mainBundle]pathForResource:fileName ofType:fileType];
        BOOL isSuccess = [fileManager copyItemAtPath:defaultDBPath toPath:DBPath error:&error];
        if (!isSuccess)
        {
            NSLog(@"Create appSetting info Failed");
        }
    }
}

#pragma mark - 将资源文件的数据库文件写入沙盒
+ (void)copyDatabaseIfNeededWithFile:(NSString *)fileName SearchPathDirectory:(NSSearchPathDirectory)searchPathDirectory
{
    NSFileManager * fileManager = [NSFileManager defaultManager];
    NSError * error;
    
    NSArray * paths = NSSearchPathForDirectoriesInDomains(searchPathDirectory, NSUserDomainMask, YES);
    
    NSString * document = [paths firstObject];
    NSString * DBPath = [document stringByAppendingPathComponent:fileName];
    BOOL success = [fileManager fileExistsAtPath:DBPath];
    if (!success)
    {
        NSString * defaultDBPath = [[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:fileName];
        success = [fileManager copyItemAtPath:defaultDBPath toPath:DBPath error:&error];
        if (!success)
        {
            NSAssert1(0, @"Fail to create writable database file with message '%@'.", [error localizedDescription]);
        }
    }
}

#pragma mark - 创建或向已存在的Plist文件写数据（数组）
+ (void)updatePlist:(NSSearchPathDirectory)searchPathDirectory WithFile:(NSString *)filename WithArray:(NSArray *)infoArray
{
    //获取Document或者Library目录
    NSArray * paths = NSSearchPathForDirectoriesInDomains(searchPathDirectory, NSUserDomainMask, YES);
    
    NSString * documents = [paths firstObject];
    
    //获取文件路径
    NSFileManager * fileManager = [NSFileManager defaultManager];
    NSString * plistPath = [documents stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",filename]];
    
    //指定路径下的文件不存在 先创建文件再向文件中写数据，如果文件存在就直接写入数据
    if (![fileManager fileExistsAtPath:plistPath])
    {
        [[NSFileManager defaultManager] createFileAtPath:plistPath contents:nil attributes:nil];
    }
    [infoArray writeToFile:plistPath atomically:YES];
}

#pragma mark - 创建货向已存在的Plist文件写数据（字典）
+ (void)updatePlist:(NSSearchPathDirectory)searchPathDirectory WithFile:(NSString *)filename WithDictionary:(NSDictionary *)infoDict
{
    //获取Document或者Library目录
    NSArray * paths = NSSearchPathForDirectoriesInDomains(searchPathDirectory, NSUserDomainMask, YES);
    
    NSString * documents = [paths firstObject];
    
    //获取文件路径
    NSFileManager * fileManager = [NSFileManager defaultManager];
    NSString * plistPath = [documents stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",filename]];
    
    //指定路径下的文件不存在 先创建文件再向文件中写数据，如果文件存在就直接写入数据
    if (![fileManager fileExistsAtPath:plistPath])
    {
        [[NSFileManager defaultManager] createFileAtPath:plistPath contents:nil attributes:nil];
    }
    [infoDict writeToFile:plistPath atomically:YES];
}

#pragma mark - 更新Plist文件（根目录文件为字典）一级目录的某一个字段的内容
+ (void)updatePlist:(NSSearchPathDirectory)searchPathDirectory WithFile:(NSString *)filename WithKey:(NSString *)key WithValue:(id)value
{
    NSMutableDictionary * info = [self readDictionaryPlistForKey:searchPathDirectory WitFile:filename];
    if (!info)
    {
        info = [NSMutableDictionary dictionary];
    }
    [info setObject:value forKey:key];
    [self updatePlist:searchPathDirectory WithFile:filename WithDictionary:info];
}

#pragma mark - 获取Plist文件（根目录为字典）的一级目录下某个字段
+ (NSString *)readPlistForKey:(NSSearchPathDirectory)searchPathDirectory WithFile:(NSString *)filename WithKey:(NSString *)key
{
    NSMutableDictionary * info = [self readDictionaryPlistForKey:searchPathDirectory WitFile:filename];
    NSString * readInfo = [info objectForKey:key];
    return readInfo;
}

@end
